/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.bcps;

import cn.ac.iie.di.datadock.rdata.exchange.client.v1.session.RESendSession;
import cn.ac.iie.di.global.GlobalParas;
import cn.ac.iie.di.tools.FileTools;
import cn.ac.iie.di.tools.MMUrlPath;
//import cn.ac.iie.di.bcps.JsonBcpsSender.ClientPool;
import cn.ac.iie.di.tools.JedisConnectionHandler;
import cn.ac.iie.di.tools.MppJdbcPool_dbcp;
import iie.mm.client.ClientAPI;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;

/**
 *
 * @author lenovo-pc
 */
public class JsonBcpsTask implements Runnable {
    
    private final List<String> jsonList;
    
    static private final HashMap<String, String> JsonData;//存储Json中的数据
    static org.apache.log4j.Logger logger = null;
    
    static {
        logger = org.apache.log4j.Logger.getLogger(JsonBcpsTask.class.getName());
    }
    
    private SimpleDateFormat formatter;
    
    static {
        
        JsonData = new HashMap<>();
        
    }
//    private final ClientPool pool;

    public JsonBcpsTask(List<String> jsonList) {
        this.jsonList = jsonList;
//        this.pool = pool;
        this.formatter = new SimpleDateFormat("yyyy-MM");
    }
    
    @Override
    public void run() {
        Jedis session = null;
//        ClientAPI pcInfos = null;
        try {
//            session = GlobalParas.pool.borrowSession();
            long start1 = System.currentTimeMillis();
            logger.info("get id redis client");
            session = GlobalParas.connectionHandler.getJedis();
            logger.info("get idRedis time " + (System.currentTimeMillis() - start1));
            int num = 0;
//            pcInfos = GlobalParas.pool.borrowSession();
//            session.incrBy(key, 0);
            for (String zipJson : jsonList) {
                num++;
                String json = null;
                if (zipJson.contains("$")) {
                    json = zipJson.split("=")[1].split("\\$")[0];
                } else {
                    json = zipJson.split("=")[1];
                }
                
                String dir = zipJson.split("=")[0];
                logger.info("the zipJson is :" + zipJson);
                if (json != null && !json.isEmpty()) {
                    JSONObject object;
                    try {
                        object = JSONObject.fromObject(json);
                        String id = object.get("opid").toString();
                        logger.info("the id is : " + id);
                        String str = session.get(id);
                        if (null == str) {
                            Thread.sleep(5000);
                            str = session.get(id);
                        }
                        logger.info("this redis get id is: " + str);
                        
                        String g_id = null;
                        if (null == str) {
//                            logger.info("redis dont get is " + id + " redis client is : " + session.info());
                            logger.info("redis dont get is " + id);
                            while (GlobalParas.retryQueue.offer(zipJson + "$" + (System.currentTimeMillis() / 1000))) {
                                logger.info("GlobalParas.retryQueue Size: " + GlobalParas.retryQueue.size());
                                Thread.sleep(3000);
                            }

//                            FileTools.deleteDir(new File(GlobalParas.TMP_NEWS + File.separator + dir));
                            continue;
                        }
                        if (str.contains("_")) {
                            g_id = str.split("_")[0];
                            Long time = Long.valueOf(str.split("_")[1]);
                            logger.info("get file time is : " + (System.currentTimeMillis() / 1000 - time));
                        } else {
                            g_id = str;
                        }
                        
                        JSONArray jaArray = object.getJSONArray("subResults");
                        for (int i = 0; i < jaArray.size(); i++) {
                            JSONObject jo = (JSONObject) jaArray.get(i);
                            JSONObject data = JSONObject.fromObject(jo.get("data").toString().substring(1, jo.get("data").toString().length()));
                            File jpg = new File(GlobalParas.TMP_NEWS + File.separator + dir + File.separator + data.get("filename"));
                            
                            logger.info("the jpg path is : " + jpg.getPath());
                            long mediaTime = System.currentTimeMillis();
                            JSONObject joj = new JSONObject();
                            joj.put("type", jpg.getName().split("\\.")[1]);
                            joj.put("g_id", g_id);
                            if (g_id.contains("@")) {
                                joj.put("table", "tp_wxq_media");
                            } else {
                                joj.put("table", "tp_wxq_target_v1");
                            }
                            
                            logger.info("the json is " + joj.toString());
                            String key = GlobalParas.pcInfo.uploadFile(jpg.getPath(), joj.toString());
                            logger.info("Media Time is : " + (System.currentTimeMillis() - mediaTime));
                            logger.info("media return key : " + key);
                            if (null == key) {
                                logger.info("media is loser!");
                                FileTools.deleteDir(new File(GlobalParas.TMP_NEWS + File.separator + dir));
                                continue;
                            }
                            if (g_id.contains("@")) {
                                logger.info("No updates mpp");
                                FileTools.deleteDir(new File(GlobalParas.TMP_NEWS + File.separator + dir));
//                                Long delNum = session.del(id);
//                                logger.info("delNum: " + delNum + " id: " + id);
                                continue;
                            }
                            long start2 = System.currentTimeMillis();
                            Connection mppcon = null;
                            for (int j = 0; j < 10; j++) {
                                try {
                                    mppcon = MppJdbcPool_dbcp.getConnection();
                                    if (mppcon != null) {
                                        break;
                                    }
                                    Thread.sleep(3000);
                                } catch (Exception e) {
                                    logger.error("mpp num " + j + " error " + e, e);
                                }
                            }
                            String updsql = "update tp_wxq_target_v1 set m_mm_content='" + key + "' where g_id='" + g_id + "';";
                            logger.info("the update Sql is" + updsql);
                            if (null == mppcon) {
                                logger.info("mppcon is null ");
                                FileTools.deleteDir(new File(GlobalParas.TMP_NEWS + File.separator + dir));
                                continue;
                            }
                            PreparedStatement upps = mppcon.prepareStatement(updsql);
//                            upps.setString(1, key);
//                            upps.setString(2, g_id);
                            int intrees = upps.executeUpdate();
                            logger.info("intrees: "+intrees);
                            upps.close();
                            MppJdbcPool_dbcp.removeConn(mppcon);
                            logger.info("Update Msg Success");
                            logger.info("mpp time is : " + (System.currentTimeMillis() - start2) + " ms");
                            FileTools.deleteDir(new File(GlobalParas.TMP_NEWS + File.separator + dir));
//                            Long delNum = session.del(id);
//                            logger.info("delNum: " + delNum + " id: " + id);
                        }
                    } catch (Exception e) {
                        logger.error("The json is :" + json, e);
//                        return;
                    }
                    
                }
            }
            logger.info("All parse complete time " + (System.currentTimeMillis() - start1) + " num: " + num);
        } catch (Exception ex) {
            logger.error("know Bcp Task error ", ex);
            ex.printStackTrace();
        } finally {
            if (session != null) {
//                GlobalParas.pool.returnSession(session);
//                GlobalParas.pool.returnSession(pcInfos);
                JedisConnectionHandler.returnResource(session);
            }
        }
    }
    
}
